import sys
import os
import time
import threading
# import termios
# import tty
import cv2
import pyprind
import numpy as np
from PIL import Image  # 图片处理模块
import argparse

# 基类
class CharFrame(object):
    ascii_char = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "

    # 像素映射到字符
    def pixelToChar(self, luminance):
        return self.ascii_char[int(luminance/256*len(self.ascii_char))]

    # 将普通帧转为 ASCII 字符帧
    # limitSize 参数接受一个元组，表示图片的限宽限高。
    # fill 表示是否用空格填充图片宽度至限宽，wrap 表示是否在行末添加换行符
    def convert(self, img, limitSize=-1, fill=False, wrap=False):
        if limitSize != -1 and (img.shape[0] > limitSize[1] or img.shape[1] > limitSize[0]):
            img = cv2.resize(img, limitSize, interpolation=cv2.INTER_AREA)
        ascii_frame = ''
        blank = ''
        if fill:
            blank += ' '*(limitSize[0]-img.shape[1])
        if wrap:
            blank += '\n'
        for i in range(img.shape[0]): # shape 为元组 图片的（宽，高）
            for j in range(img.shape[1]):
                ascii_frame += self.pixelToChar(img[i,j])
            ascii_frame += blank
        return ascii_frame

'''
    图片转字符画

'''
#
class I2Char(CharFrame):
    def __init__(self, path, limitSize=-1, fill=False, wrap=False):
        self.genCharImage(path, limitSize, fill, wrap)

    def genCharImage(self, path, limitSize=-1, fill=False, wrap=False):

        # 将普通帧转为 ASCII 字符帧
        self.result = ''
        ascii_frame = self.convert(path, limitSize=-1, fill=False, wrap=False)
        # 给self.result 字符画字符串赋值
        self.result += ascii_frame
 

    def show(self, stream = 2):
        if self.result is None:
            return
        if stream == 1 and os.isatty(sys.stdout.fileno()):
            self.streamOut = sys.stdout.write
            self.streamFlush = sys.stdout.flush
        elif stream == 2 and os.isatty(sys.stderr.fileno()):
            self.streamOut = sys.stderr.write
            self.streamFlush = sys.stderr.flush
        elif hasattr(stream, 'write'):
            self.streamOut = stream.write
            self.streamFlush = stream.flush
        self.streamOut(self.result)
        self.streamFlush()
        self.streamOut('\n')


if __name__ == '__main__':

    # 命令行输入参数处理
    parser = argparse.ArgumentParser()
    parser.add_argument('file')  # 输入文件
    #
    # 获取参数
    args = parser.parse_args()
    IMG_name = args.file

    # img = Image.open(IMG_name)
    # img_array = np.array(img)
    # print(img_array[:,:,0])
	# i2char = I2Char(img_array)
    # i2char.show()
	
	img = cv2.imread(IMG_name,cv2.IMREAD_GRAYSCALE)
	i2char = I2Char(img)
	i2char.show()

#     '''
#         通过命令行调用图片转字符画功能 ,命令行执行 Python v2char.py t3.jpeg,输出字符画
#     '''






